package com.xuxueli.applyModules.commont.testEntityFeids;

import org.springframework.beans.factory.annotation.Value;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.nio.charset.Charset;

/**
 * @date: 2019-05-16
 */
public class XdoSizeValidator implements ConstraintValidator<XdoSize, String> {

    @Value("${dc.db.charset:GBK}")
    private String charset;

    private XdoSize size;

    @Override
    public void initialize(XdoSize constraintAnnotation) {
        this.size = constraintAnnotation;
    }

    /**
     * Implements the validation logic.
     * The state of {@code value} must not be altered.
     * <p>
     * This method can be accessed concurrently, thread-safety must be ensured
     * by the implementation.
     *
     * @param value   object to validate
     * @param context context in which the constraint is evaluated
     * @return {@code false} if {@code value} does not pass the constraint
     */
    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        if (value == null || "".equals(value)) {
            return size.min() == 0 ? true : false;
        }
        int length;
        try {
            length = value.getBytes(charset).length;
        } catch (Exception e) {
            try {
                length = value.getBytes(Charset.forName("GBK")).length;
            } catch (Exception e1){
                // 如果失败，虚拟机就直接狗带了，不需要了
                length = value.getBytes().length;
            }
        }
        return (length > size.max() || length < size.min()) ? false : true;
    }
}
